package com.jxzyk.http;

import java.io.UnsupportedEncodingException;

import org.apache.http.entity.StringEntity;

import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.core.entity.params.JsonParams;
import com.core.entity.params.MapParams;
import com.core.entity.params.ReqParams;
import com.core.util.L;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class HttpTools {

	private HttpUtils httpUtils;
	private boolean FLAG = true;
	private String TAG = "HttpTools";

	public interface OnHttpListener {
		void onSuccess(JSONObject json);

		void onFailure();
	}

	public HttpTools() {
		httpUtils = new HttpUtils();
	}

	public void get(String url, final OnHttpListener listener) {
		httpUtils.send(HttpMethod.GET, url, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				listener.onFailure();
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				listener.onSuccess(new JSONObject().parseObject(arg0.result));
			}
		});
	}

	public void post(String url, ReqParams params, final OnHttpListener listener) {
		try {
			if (FLAG) {
				L.d("URL[" + url + "]\nParams[" + params.toLog()
						+ "]\nCharset[" + params.toValue().getCharset() + "]");
			}
			httpUtils.send(HttpMethod.POST, url, params.toValue(),
					new RequestCallBack<String>() {

						@Override
						public void onFailure(HttpException arg0, String arg1) {
							listener.onFailure();
							if (FLAG) {
								L.d("[HTTP RSP]:" + arg1);
							}
						}

						@Override
						public void onSuccess(ResponseInfo<String> arg0) {
							String data = null;
							data = arg0.result;
							if (FLAG) {
								L.d("[HTTP RSP]:" + data);
							}
							if (!TextUtils.isEmpty(data)) {
								listener.onSuccess(new JSONObject()
										.parseObject(arg0.result));
							} else {
								L.d("[HTTP RSP]:数据为空");
								listener.onFailure();
							}
						}
					});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
